<template>
  <view class="container">
    <view class="title">基本信息</view>
    <u-form labelWidth="220" :model="form" ref="uForm" label-position="top">
      <u-form-item label="班级类型" prop="classType" :border-bottom="false">
        <view class="class-type-selector">
          <view 
            v-for="item in classList" 
            :key="item.value" 
            class="class-type-item"
            :class="{ 'class-type-active': form.classType === item.value }"
            @click="selectClassType(item)"
          >
            <view class="radio-circle">
              <view class="radio-inner" v-if="form.classType === item.value"></view>
            </view>
            <text>{{ item.label }}</text>
          </view>
        </view>
      </u-form-item>
      <u-form-item label="上课时间" prop="startTime">
        <u-input v-model="form.startTime" placeholder="请选择" :clearable="false" @click="openCalendar('start')"></u-input>
        <u-icon @click="openCalendar('start')" class="suffix-icon" name="calendar" size="28"></u-icon>
      </u-form-item>
      <u-form-item label="上课时长" prop="duration">
        <!-- 三种时长选项，强制分行显示 -->
        <view style="display: block; width: 100%">
          <!-- 分钟输入框 -->
          <view style="display: block; width: 100%; margin-bottom: 30rpx; padding: 20rpx; border: 1px solid #eee; border-radius: 8rpx">
            <view style="display: flex; align-items: center">
              <u-input v-model="form.duration_minutes" placeholder="请输入分钟" type="number" :border="true" :maxlength="2" />
              <text style="margin-left: 15rpx">分钟</text>
            </view>
          </view>

          <!-- 小时选项 -->
          <view style="display: block; width: 100%; margin-bottom: 30rpx; padding: 20rpx; border: 1px solid #eee; border-radius: 8rpx">
            <view style="margin-bottom: 10rpx">
              <u-checkbox v-model="showHoursDuration" @change="toggleHoursDuration">小时</u-checkbox>
            </view>
            <view v-if="showHoursDuration" style="display: flex; align-items: center">
              <u-input v-model="form.duration_hours" placeholder="请输入小时" type="number" :border="true" :maxlength="2" />
              <text style="margin-left: 15rpx">小时</text>
            </view>
          </view>
        </view>
      </u-form-item>

      <!-- 上课前成班截止时间 -->
      <u-form-item label="上课前成班截止时间" prop="before_class_hours">
        <view style="display: block; width: 100%">
          <!-- 分钟输入框 -->
          <view style="display: block; width: 100%; margin-bottom: 30rpx; padding: 20rpx; border: 1px solid #eee; border-radius: 8rpx">
            <view style="display: flex; align-items: center">
              <u-input v-model="form.before_class_minutes" placeholder="请输入分钟" type="number" :border="true" :maxlength="2" />
              <text style="margin-left: 15rpx">分钟</text>
            </view>
          </view>

          <!-- 小时输入框 -->
          <view style="display: block; width: 100%; margin-bottom: 30rpx; padding: 20rpx; border: 1px solid #eee; border-radius: 8rpx">
            <view style="margin-bottom: 10rpx">
              <u-checkbox v-model="showBeforeClassHours" @change="toggleBeforeClassHours">小时</u-checkbox>
            </view>
            <view v-if="showBeforeClassHours" style="display: flex; align-items: center">
              <u-input v-model="form.before_class_hours" placeholder="请输入小时" type="number" :border="true" :maxlength="2" />
              <text style="margin-left: 15rpx">小时</text>
            </view>
          </view>
        </view>
      </u-form-item>

      <!-- 精品班成班截止时间 -->
      <u-form-item label="精品班成班截止时间" prop="boutique_before_class_hours">
        <view style="display: block; width: 100%">
          <!-- 分钟输入框 -->
          <view style="display: block; width: 100%; margin-bottom: 30rpx; padding: 20rpx; border: 1px solid #eee; border-radius: 8rpx">
            <view style="display: flex; align-items: center">
              <u-input v-model="form.boutique_before_class_minutes" placeholder="请输入分钟" type="number" :border="true" :maxlength="2" />
              <text style="margin-left: 15rpx">分钟</text>
            </view>
          </view>

          <!-- 小时输入框 -->
          <view style="display: block; width: 100%; margin-bottom: 30rpx; padding: 20rpx; border: 1px solid #eee; border-radius: 8rpx">
            <view style="margin-bottom: 10rpx">
              <u-checkbox v-model="showBoutiqueBeforeClassHours" @change="toggleBoutiqueBeforeClassHours">小时</u-checkbox>
            </view>
            <view v-if="showBoutiqueBeforeClassHours" style="display: flex; align-items: center">
              <u-input v-model="form.boutique_before_class_hours" placeholder="请输入小时" type="number" :border="true" :maxlength="2" />
              <text style="margin-left: 15rpx">小时</text>
            </view>
          </view>
        </view>
      </u-form-item>

      <u-form-item label="参与人数范围" prop="minParticipants">
        <view class="range-container">
          <u-input v-model="form.minParticipants" placeholder="最小人数" type="number" :border="true" />
          <view class="range-separator">-</view>
          <u-input v-model="form.maxParticipants" placeholder="最大人数" type="number" :border="true" />
        </view>
      </u-form-item>
      
      <!-- 添加精品班最低成班人数字段 -->
      <u-form-item label="精品班最低成班人数" prop="boutiqueMinUsers">
        <u-input v-model="form.boutiqueMinUsers" placeholder="请输入精品班最低成班人数" type="number" :border="true" />
      </u-form-item>

      <view class="title margin-top">课程设置</view>
      <u-form-item label="课程分类" prop="courseCategory">
        <u-input type="select" v-model="form.courseCategoryName" placeholder="请选择课程分类" @click="showCategorySelect = true" />
      </u-form-item>
      <u-form-item label="课程名称" prop="courseName">
        <u-input
          type="select"
          v-model="form.courseName"
          placeholder="请选择课程名称"
          @click="checkAndShowCourseSelect"
          :disabled="!form.courseCategoryId"
        />
      </u-form-item>
      <u-form-item label="上课地点" prop="locationName">
        <view class="inputview" @click="chooseMap">
          <view>{{ form.locationName || '请选择上课地点' }}</view>
          <u-icon class="suffix-icon" name="map-fill" size="28"></u-icon>
        </view>
      </u-form-item>
      <template v-if="form.classType == 3 || form.classType == 4">
        <u-form-item label="上课星期" prop="weekdays">
          <view class="weekdays-container">
            <view v-for="(day, index) in weekList" :key="index" class="weekday-item">
              <u-checkbox v-model="selectedWeekdays[index]" @change="val => updateWeekdays(index, val)">{{ day.text }}</u-checkbox>
            </view>
          </view>
        </u-form-item>
        <u-form-item label="总周期数" prop="totalCycles">
          <u-input v-model="form.totalCycles" placeholder="请输入总周期数" type="number" />
        </u-form-item>
      </template>

      <view class="title margin-top">高级设置</view>
      <!-- <view class="setting-item">
        <view class="setting-label">是否启用虚拟人数</view>
        <u-switch v-model="form.virtualParticipants" active-color="#2979ff"></u-switch>
      </view>
      <view class="setting-desc">启用虚拟人数可以帮助快速达到班级最低参加人数，有助于创建和启动课程</view> -->

      <!-- <view class="setting-item">
        <view class="setting-label">是否启用优惠券</view>
        <u-switch v-model="form.couponEnabled" active-color="#2979ff"></u-switch>
      </view> -->

      <view class="setting-item">
        <view class="setting-label">是否启用新人价</view>
        <u-switch v-model="form.newPriceEnabled" active-color="#2979ff"></u-switch>
      </view>
<!-- 
      <view class="setting-item">
        <view class="setting-label">是否添加免单学员</view>
        <u-switch v-model="form.isFree" active-color="#2979ff" @change="toggleFreeStudent"></u-switch>
      </view>

      <view v-if="form.isFree">
        <u-form-item label="免单学员" prop="freeStudentId">
          <u-input @click="addStudent" v-model="form.freeStudentName" placeholder="请选择免单学员" />
          <u-icon @click="addStudent" class="suffix-icon" name="account-fill" size="28"></u-icon>
        </u-form-item>
      </view> -->
    </u-form>
    <view class="box action_btn">
      <view class="btn btn1" @click="resetForm">重置</view>
      <view class="btn btn2" @click="submitGroupClass">提交</view>
    </view>
    <!-- 时间选择 -->
    <u-picker mode="time" v-model="showCalendar" @confirm="calendarConfirm" :params="timeParams"></u-picker>

    <!-- 类型选择器 -->
    <u-select v-if="!multiple" v-model="showSelect" mode="single-column" :list="selectList" @confirm="selectConfirm"></u-select>

    <!-- 课程分类选择器 -->
    <u-select v-model="showCategorySelect" :list="courseCategories" @confirm="selectCategoryConfirm" mode="single-column"></u-select>

    <!-- 课程名称选择器 -->
    <u-select v-model="showCourseSelect" :list="courseList" @confirm="selectCourseConfirm" mode="single-column"></u-select>

    <!-- 地图 -->
    <u-popup mode="top" width="100%" height="100%" v-model="showMap" @open="openMap">
      <map-selector ref="mapSelector" @select="handlerSelectMap" @cancel="showMap = false" />
    </u-popup>

    <!-- 成功弹窗 -->
    <u-popup v-model="showSuccessPopup" mode="center" width="80%" :maskCloseAble="false">
      <view class="success-popup">
        <view class="success-icon">
          <u-icon name="checkmark-circle" color="#0dc160" size="64"></u-icon>
        </view>
        <view class="success-title">创建成功</view>
        <view class="success-desc">您已成功发起拼班，请选择下一步操作</view>
        <view class="success-actions">
          <view class="success-btn primary" @click="goToInviteTeacher">去邀请陪伴师</view>
          <view class="success-btn default" @click="goToHomePage">进入主页</view>
          <view class="success-btn link" @click="continueCreateClass">继续发起拼班</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
import { createGroupClass, getCourseCategories, getCoursesByCategory, getClassTypes } from '@/api/class_share';
import Cache from '@/utils/cache';
import mapSelector from '@/components/map/index.vue';
import { baseURL } from '@/config/app.js';
export default {
  components: {
    mapSelector,
  },
  data() {
    return {
      show: false,
      showMap: false,
      timeParams: {
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: false,
      },
      courseList: [
        {
          label: '健身课',
          value: '1',
        },
        {
          label: '拳击课',
          value: '2',
        },
        {
          label: '公益课',
          value: '3',
        },
      ],
      classList: [
        {
          label: '周期班',
          value: '3',
        },
        {
          label: '定制班',
          value: '4',
        },
      ],
      multiple: false,
      // 周期班\定制班
      weekList: [
        { value: '1', text: '周一' },
        { value: '2', text: '周二' },
        { value: '3', text: '周三' },
        { value: '4', text: '周四' },
        { value: '5', text: '周五' },
        { value: '6', text: '周六' },
        { value: '7', text: '周日' },
      ],
      form: {
        classType: '3', // 默认选择周期班
        className: '周期班',
        courseCategoryId: '',
        courseCategoryName: '',
        courseName: '',
        courseId: '',
        coachId: '',
        startTime: '',
        duration: '',
        duration_hours: '', // 单次课时长（小时）
        duration_minutes: '',
        enrollmentDeadline: '',
        before_class_hours: '', // 默认不设置小时数
        before_class_minutes: '0', // 默认0分钟
        boutique_before_class_hours: '', // 默认不设置小时数
        boutique_before_class_minutes: '0', // 默认0分钟
        boutiqueMinUsers: '1', // 精品班最低成班人数，默认为1
        locationName: '',
        location: {
          name: '',
          province: '',
          city: '',
          district: '',
          address: '',
          longitude: '',
          latitude: '',
        },
        weekdays: [],
        weekDayName: '',
        totalCycles: '',
        minParticipants: '',
        maxParticipants: '',
        virtualParticipants: false, // 启用虚拟人数
        couponEnabled: false, // 启用优惠券
        newPriceEnabled: false, // 启用新人价
        isFree: false, // 免单学员
        freeStudentId: '', // 免单学员ID
        freeStudentName: '',
        paymentType: '', // 支付类型:1=单次支付,2=周期代扣,3=全款支付
        status: 0, // 状态:0=待成班,1=已成班,2=进行中,3=已结束,4=已取消
        minIncome: '',
        maxIncome: '',
      },
      calendarType: '',
      showCalendar: false,
      mode: 'date', // 改回 date 模式
      showSelect: false,
      selectList: [],
      selectType: 1,
      rules: {
        classType: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        courseCategory: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],

        courseId: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        coachId: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        startTime: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        duration: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ], // 单次课时长（小时）
        enrollmentDeadline: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        before_class_hours: [
          {
            required: true,
            message: '请输入上课前成班截止小时数',
            trigger: ['change', 'blur'],
          },
        ],
        before_class_minutes: [
          {
            required: true,
            message: '请输入上课前成班截止分钟数',
            trigger: ['change', 'blur'],
          },
        ],
        boutique_before_class_hours: [
          {
            required: true,
            message: '请输入精品班上课前截止小时数',
            trigger: ['change', 'blur'],
          },
        ],
        boutique_before_class_minutes: [
          {
            required: true,
            message: '请输入精品班上课前截止分钟数',
            trigger: ['change', 'blur'],
          },
        ],
        locationName: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        minParticipants: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        maxParticipants: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        freeStudentId: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
      },
      showHoursDuration: false,
      showDaysDuration: false,
      showBeforeClassHours: false, // 默认不选择小时
      showBoutiqueBeforeClassHours: false, // 默认不选择小时
      selectedWeekdays: [false, false, false, false, false, false, false],
      // 课程分类列表
      courseCategories: [],
      // 当前分类下的课程列表
      courseList: [],
      // 选择器控制
      showCategorySelect: false,
      showCourseSelect: false,
      mapUrl: baseURL + '/admin/map',
      showSuccessPopup: false,
      createdClassId: null,
      scheduleId: null,
    };
  },
  onReady() {
    // Cache.set('COUCHID', '');
    // this.$refs.uForm.setRules(this.rules);
  },
  onLoad() {
    const form = Cache.get('initiateForm');
    if (form) {
      this.form = JSON.parse(form);
    }
    const student = JSON.parse(Cache.get('STUDENTID'));
    if (student) {
      this.form.freeStudentId = student.id;
      this.form.freeStudentName = student.name;
    }
    console.log('页面加载');
    this.fetchCourseCategories();
    this.fetchClassTypes(); // 获取班级类型列表
    uni.$on('locationConfirm', obj => {
      console.log('addressObj', obj);
      this.handlerSelectMap(obj);
    });
  },
  methods: {
    chooseMap() {
      // #ifdef APP
      this.$Router.push({
        path: `/components/web-view/web-view`,
        query: {
          url: encodeURIComponent(this.mapUrl)
        }
      })
      // #endif
      // #ifdef H5
      this.showMap = true
      // #endif
    },
    toggleHoursDuration(e) {
      this.showHoursDuration = e;
      if (!e) {
        this.form.duration_hours = '';
      }
    },
    toggleBeforeClassHours(e) {
      this.showBeforeClassHours = e;
      if (!e) {
        this.form.before_class_hours = '';
      }
    },
    toggleBoutiqueBeforeClassHours(e) {
      this.showBoutiqueBeforeClassHours = e;
      if (!e) {
        this.form.boutique_before_class_hours = '';
      }
    },
    toggleFreeStudent(e) {
      if (!e) {
        this.form.freeStudentId = '';
        this.form.freeStudentName = '';
      }
    },
    updateWeekdays(index, value) {
      this.selectedWeekdays[index] = value;

      const weekdays = [];
      const weekdayNames = [];

      this.selectedWeekdays.forEach((selected, idx) => {
        if (selected) {
          weekdays.push(this.weekList[idx].value);
          weekdayNames.push(this.weekList[idx].text);
        }
      });

      this.form.weekdays = weekdays;
      this.form.weekDayName = weekdayNames.join(', ');
    },
    addStudent() {
      Cache.set('initiateForm', JSON.stringify(this.form));
      uni.navigateTo({
        url: '/pages/student_manage/student_manage',
      });
    },
    showActionSheet(type) {
      if (type !== 1) {
        this.selectType = type;
        this.multiple = type === 4;
        this.showSelect = true;
        switch (type) {
          case 2:
            this.selectList = this.courseList;
            break;
          case 3:
            this.selectList = this.weekList;
            break;
          case 4:
            this.selectList = this.weekList;
            break;
        }
      }
    },
    selectConfirm(res) {
      this.showSelect = false;
      const data = res[0];

      switch (this.selectType) {
        case 1:
          this.form.classType = data.value;
          this.form.className = data.label;
          break;
        case 2:
          this.form.courseCategoryName = data.label;
          this.form.courseId = data.value;
          break;
        case 3:
          this.form.weekdays = res.map(item => item.value);
          this.form.weekDayName = res.map(item => item.label).join('、');
          break;
        case 4:
          this.form.weekdays = res.map(item => item.value);
          this.form.weekDayName = res.map(item => item.label).join('、');
          break;
      }
    },

    resetForm() {
      this.form = {
        classType: '3', // 默认选择周期班
        className: '周期班',
        courseCategoryId: '',
        courseCategoryName: '',
        courseName: '',
        courseId: '',
        coachId: '',
        startTime: '',
        duration: '',
        duration_hours: '', 
        duration_minutes: '',
        enrollmentDeadline: '',
        before_class_hours: '', // 默认不设置小时数
        before_class_minutes: '0', // 默认0分钟
        boutique_before_class_hours: '', // 默认不设置小时数
        boutique_before_class_minutes: '0', // 默认0分钟
        boutiqueMinUsers: '1', // 精品班最低成班人数，默认为1
        locationName: '',
        location: {
          name: '',
          province: '',
          city: '',
          district: '',
          address: '',
          longitude: '',
          latitude: '',
        },
        weekdays: [],
        weekDayName: '',
        totalCycles: '',
        minParticipants: '',
        maxParticipants: '',
        virtualParticipants: false,
        couponEnabled: false,
        newPriceEnabled: false,
        isFree: false,
        freeStudentId: '',
        freeStudentName: '',
        paymentType: '',
        status: 0,
        minIncome: '',
        maxIncome: '',
      };
      this.selectedWeekdays = [false, false, false, false, false, false, false];
      this.showHoursDuration = false;
      this.showDaysDuration = false;
      this.showBeforeClassHours = false; // 重置为不选择小时
      this.showBoutiqueBeforeClassHours = false; // 重置为不选择小时
      
      uni.showToast({
        title: '表单已重置',
        icon: 'none'
      });
    },

    submitGroupClass() {
      // 表单验证
      if (!this.form.courseId) {
        uni.showToast({
          title: '请选择课程',
          icon: 'none',
        });
        return;
      }

      // 检查地址信息
      if (!this.form.locationName || !this.form.location) {
        uni.showToast({
          title: '请选择上课地点',
          icon: 'none',
        });
        return;
      }
      
      // 验证精品班最低成班人数不能大于普通班最低成班人数
      const boutiqueMinUsers = parseInt(this.form.boutiqueMinUsers || 1);
      const minParticipants = parseInt(this.form.minParticipants || 0);
      
      if (boutiqueMinUsers > minParticipants) {
        uni.showToast({
          title: '精品班最低成班人数不能大于普通班最低成班人数',
          icon: 'none',
          duration: 3000
        });
        return;
      }
      
      // 验证上课前成班截止时间必须大于精品班成班截止时间
      const normalMinutes = this.calculateTotalMinutes(this.form.before_class_hours, this.form.before_class_minutes);
      const boutiqueMinutes = this.calculateTotalMinutes(this.form.boutique_before_class_hours, this.form.boutique_before_class_minutes);
      
      // 如果两个时间都设置了，才进行比较
      if (normalMinutes > 0 && boutiqueMinutes > 0 && normalMinutes <= boutiqueMinutes) {
        uni.showToast({
          title: '上课前成班截止时间必须大于精品班成班截止时间',
          icon: 'none',
          duration: 3000
        });
        return;
      }

      // 确保location对象格式正确
      const location = {
        name: this.form.locationName || this.form.location.name || '',
        address: this.form.location.address || this.form.locationName || '',
        province: this.form.location.province || '',
        city: this.form.location.city || '',
        district: this.form.location.district || '',
        longitude: this.form.location.longitude || '',
        latitude: this.form.location.latitude || '',
      };

      // 构建提交数据
      const submitData = {
        classType: this.form.classType,
        className: this.form.className,
        courseCategoryId: this.form.courseCategoryId,
        courseId: this.form.courseId,
        courseName: this.form.courseName,
        startTime: this.form.startTime,
        duration_hours: this.form.duration_hours || 0,
        duration_minutes: this.form.duration_minutes || 0,
        enrollmentDeadline: this.form.enrollmentDeadline,
        before_class_hours: this.form.before_class_hours || 0,
        before_class_minutes: this.form.before_class_minutes || 0,
        boutique_before_class_hours: this.form.boutique_before_class_hours || 0,
        boutique_before_class_minutes: this.form.boutique_before_class_minutes || 0,
        boutiqueMinUsers: this.form.boutiqueMinUsers || 1, // 添加精品班最低成班人数
        location: location,
        locationName: this.form.locationName,
        minParticipants: this.form.minParticipants,
        maxParticipants: this.form.maxParticipants,
        virtualParticipants: this.form.virtualParticipants,
        couponEnabled: this.form.couponEnabled,
        newPriceEnabled: this.form.newPriceEnabled,
        isFree: this.form.isFree,
        freeStudentId: this.form.freeStudentId,
        status: 0, // 添加状态字段，0=待匹配
        // 周期班特有字段
        ...(this.form.classType === '3' || this.form.classType === '4'
          ? {
              weekdays: this.form.weekdays,
              totalCycles: this.form.totalCycles,
            }
          : {}),
      };

      console.log('提交的数据:', submitData);

      // 发送请求
      createGroupClass(submitData)
        .then(res => {
          console.log('创建拼班成功:', res);
          console.log('API完整返回数据:', JSON.stringify(res));
          
          // 正确获取返回数据，考虑可能的嵌套结构
          let responseData = res;
          if (res.data && typeof res.data === 'object') {
            responseData = res.data;
          }
          
          this.createdClassId = responseData.class_id || null;
          this.scheduleId = responseData.schedule_id || null;
          
          console.log('获取到班级ID:', this.createdClassId);
          console.log('获取到排课ID:', this.scheduleId);
          // 显示成功弹窗
          this.showSuccessPopup = true;
        })
        .catch(err => {
          console.error('创建拼班失败:', err);
          uni.showToast({
            title: '创建失败，请重试',
            icon: 'none',
          });
        });
    },
    
    // 去邀请陪伴师
    goToInviteTeacher() {
      this.showSuccessPopup = false;
      // 使用排课ID进行跳转，如果没有则使用班级ID
      const id = this.scheduleId || this.createdClassId;
      console.log('跳转使用ID:', id);
      // 跳转到陪伴师邀请页面
      uni.navigateTo({
        url: `/pages/teacher_manage/index?id=${id}`
      });
    },
    
    // 进入主页
    goToHomePage() {
      this.showSuccessPopup = false;
      this.$Router.pushTab({
        path: '/pages/class_manage/index'
      });
    },
    
    // 继续发起拼班
    continueCreateClass() {
      this.showSuccessPopup = false;
      this.resetForm();
    },

    // 计算总分钟数（用于比较截止时间）
    calculateTotalMinutes(hours, minutes) {
      const hoursValue = parseInt(hours || 0);
      const minutesValue = parseInt(minutes || 0);
      return hoursValue * 60 + minutesValue;
    },

    // 计算总时长（转换为分钟）
    calculateTotalDuration() {
      let totalMinutes = parseInt(this.form.duration_minutes || 0);

      if (this.showHoursDuration && this.form.duration_hours) {
        totalMinutes += parseInt(this.form.duration_hours) * 60;
      }

      return totalMinutes;
    },

    // 原有的方法保持不变，可以被新方法调用
    matchTeacher() {
      Cache.set('initiateForm', JSON.stringify(this.form));
      uni.navigateTo({
        url: '/pages/class_manage/index',
      });
    },
    openCalendar(type) {
      this.calendarType = type;
      this.showCalendar = true;
    },
    calendarConfirm(e) {
      console.log('日历选择返回数据:', e);

      try {
        let timestamp;
        if (e.timestamp) {
          timestamp = e.timestamp;
        } else if (e.value) {
          timestamp = new Date(e.value).getTime();
        } else if (typeof e === 'number') {
          timestamp = e;
        } else if (e.year && e.month && e.day) {
          // 处理年月日格式
          timestamp = new Date(e.year, e.month - 1, e.day, e.hour || 0, e.minute || 0).getTime();
        } else {
          console.error('无法识别的日期格式:', e);
          return;
        }

        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hours = date.getHours().toString().padStart(2, '0');
        const minutes = date.getMinutes().toString().padStart(2, '0');

        const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:00`;
        console.log('格式化后的日期时间:', formattedDate);

        if (this.calendarType === 'start') {
          this.form.startTime = formattedDate;
        } else if (this.calendarType === 'end') {
          this.form.enrollmentDeadline = formattedDate;
        }
      } catch (error) {
        console.error('日期转换错误:', error, e);
        uni.showToast({
          title: '日期格式错误，请重新选择',
          icon: 'none',
        });
      }
    },
    openMap() {
      this.$refs.mapSelector.open();
    },
    handlerSelectMap(data) {
      console.log('选择的位置详细数据:', JSON.stringify(data));
      
      // 如果data是一个包含location对象的对象，则使用它
      let locationData = data;
      
      // 处理可能的嵌套数据结构（如来自postMessage的数据）
      if (data.data && data.data.type === 'locationSelected' && data.data.location) {
        locationData = data.data.location;
        console.log('从postMessage中提取location数据:', locationData);
      } else if (data.location && typeof data.location === 'object') {
        // 数据已经是正确格式，直接使用
        console.log('直接使用data中的location数据');
      }
      
      // 确保address是字符串
      let addressStr = '';
      if (typeof locationData.address === 'string') {
        addressStr = locationData.address;
      } else if (typeof locationData.address === 'object' && locationData.address) {
        addressStr = locationData.address.name || '';
      }
      
      // 提取location对象中的经纬度
      let longitude = '';
      let latitude = '';
      
      // 1. 尝试从location对象中提取
      if (locationData.location && typeof locationData.location === 'object') {
        if (locationData.location.lng && locationData.location.lat) {
          // 直接在location对象中
          longitude = locationData.location.lng;
          latitude = locationData.location.lat;
          console.log('从location对象提取经纬度:', {lng: longitude, lat: latitude});
        }
      }
      
      // 2. 尝试从根对象中提取
      if (!longitude && !latitude && locationData.lng && locationData.lat) {
        longitude = locationData.lng;
        latitude = locationData.lat;
        console.log('从根对象提取经纬度:', {lng: longitude, lat: latitude});
      }
      
      // 3. 尝试从嵌套的position.point对象提取
      if (!longitude && !latitude && 
          locationData.position && 
          locationData.position.point && 
          locationData.position.point.longitude && 
          locationData.position.point.latitude) {
        longitude = locationData.position.point.longitude;
        latitude = locationData.position.point.latitude;
        console.log('从position.point对象提取经纬度:', {lng: longitude, lat: latitude});
      }
      
      // 4. 尝试从location.position.point对象提取
      if (!longitude && !latitude && 
          locationData.location && 
          locationData.location.position && 
          locationData.location.position.point) {
        longitude = locationData.location.position.point.longitude;
        latitude = locationData.location.position.point.latitude;
        console.log('从location.position.point对象提取经纬度:', {lng: longitude, lat: latitude});
      }
      
      console.log('最终获取的经纬度:', {longitude, latitude});
      
      // 设置表单中的位置信息
      this.form.locationName = addressStr || locationData.name || '';
      this.form.location = {
        name: locationData.name || addressStr || '',
        address: addressStr || '',
        province: locationData.province || '',
        city: locationData.city || '',
        district: locationData.district || '',
        longitude: longitude || '',
        latitude: latitude || ''
      };
      
      console.log('设置后的位置信息:', JSON.stringify(this.form.location));
      this.showMap = false;
    },
    showLocation() {
      // 使用微信小程序内置的选择位置API
      // uni.chooseLocation({
      //   success: res => {
      //     console.log('选择的位置:', res);
      //     // 更新表单中的位置信息
      //     this.form.locationName = res.name || res.address;
      //     this.form.location = {
      //       name: res.name || '',
      //       address: res.address || '',
      //       province: '', // 微信API不直接提供省市区信息
      //       city: '',
      //       district: '',
      //       longitude: res.longitude,
      //       latitude: res.latitude,
      //     };
      //   },
      //   fail: err => {
      //     console.error('选择位置失败:', err);
      //     uni.showToast({
      //       title: '选择位置失败',
      //       icon: 'none',
      //     });
      //   },
      // });
    },
    // 获取课程分类列表
    async fetchCourseCategories() {
      try {
        console.log('开始请求课程分类数据');
        const categories = await getCourseCategories();
        console.log('API返回的课程分类数据:', categories);

        if (categories && Array.isArray(categories)) {
          this.courseCategories = categories.map(item => ({
            label: item.name,
            value: item.id,
            ...item,
          }));
          console.log('格式化后的课程分类:', this.courseCategories);
        } else {
          console.error('课程分类数据格式不正确');
          uni.showToast({
            title: '获取课程分类失败',
            icon: 'none',
          });
        }
      } catch (error) {
        console.error('获取课程分类失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none',
        });
      }
    },

    // 获取班级类型列表
    async fetchClassTypes() {
      try {
        console.log('开始请求班级类型数据');
        const result = await getClassTypes();
        console.log('API返回的班级类型数据:', result);

        if (result && Array.isArray(result.data)) {
          this.classList = result.data;
          // 如果当前表单没有设置班级类型，则设置为第一个类型
          if (!this.form.classType && this.classList.length > 0) {
            this.form.classType = this.classList[0].value;
            this.form.className = this.classList[0].label;
          }
          console.log('设置班级类型:', this.form.classType, this.form.className);
        } else {
          console.log('使用默认班级类型');
          // 使用默认的班级类型列表
          this.classList = [
            { value: '3', label: '周期班' },
            { value: '4', label: '定制班' }
          ];
          if (!this.form.classType) {
            this.form.classType = '3';
            this.form.className = '周期班';
          }
        }
      } catch (error) {
        console.error('获取班级类型失败:', error);
        // 使用默认的班级类型列表
        this.classList = [
          { value: '3', label: '周期班' },
          { value: '4', label: '定制班' }
        ];
        if (!this.form.classType) {
          this.form.classType = '3';
          this.form.className = '周期班';
        }
      }
    },

    // 选择课程分类
    selectCategoryConfirm(e) {
      console.log('选择的课程分类:', e);
      const category = e[0];

      // 同时保存ID和名称
      this.form.courseCategoryId = category.value;
      this.form.courseCategoryName = category.label;

      // 重置课程相关字段
      this.form.courseId = '';
      this.form.courseName = '';

      this.showCategorySelect = false;

      // 使用ID获取该分类下的课程列表
      this.fetchCoursesByCategory(category.value);
    },

    // 获取分类下的课程列表
    async fetchCoursesByCategory(categoryId) {
      console.log('使用分类ID获取课程:', categoryId);
      try {
        const courses = await getCoursesByCategory({ category_id: categoryId });
        console.log('课程列表API返回:', courses);

        if (courses && Array.isArray(courses)) {
          this.courseList = courses.map(course => ({
            label: course.title,
            value: course.id,
            ...course,
          }));
          console.log('格式化后的课程列表:', this.courseList);
        } else {
          console.log('该分类下没有课程或数据格式不正确');
          this.courseList = [];
          uni.showToast({
            title: '该分类下暂无课程',
            icon: 'none',
          });
        }
      } catch (error) {
        console.error('获取课程列表失败:', error);
        uni.showToast({
          title: '获取课程列表失败',
          icon: 'none',
        });
      }
    },

    // 检查并显示课程选择
    checkAndShowCourseSelect() {
      if (!this.form.courseCategoryId) {
        uni.showToast({
          title: '请先选择课程分类',
          icon: 'none',
        });
        return;
      }

      if (this.courseList.length === 0) {
        uni.showToast({
          title: '该分类下暂无课程',
          icon: 'none',
        });
        return;
      }

      this.showCourseSelect = true;
    },

    // 选择课程
    selectCourseConfirm(e) {
      console.log('选择的课程:', e);
      const course = e[0];
      this.form.courseName = course.label;
      this.form.courseId = course.value;
      this.showCourseSelect = false;
    },

    // 添加新的班级类型选择方法
    selectClassType(item) {
      this.form.classType = item.value;
      this.form.className = item.label;
    },
  },
  created() {
    console.log('开始加载数据');
  },
};
</script>
<style lang="scss" scoped>
.container {
  background: #fff;
  padding: 32rpx 24rpx;
}
.input_flex {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.match_teacher {
  height: 80rpx;
  margin: 80rpx;
  border-radius: 44rpx;
  border: 2rpx solid #0dc160;

  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 30rpx;
  color: #0dc160;
  line-height: 80rpx;
  text-align: center;
  font-style: normal;
}
.title {
  display: flex;
  align-items: center;
  height: 100%;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 30rpx;

  &:before {
    display: block;
    width: 5rpx;
    height: 38rpx;
    background-color: #50b164;
    margin-right: 10rpx;
    content: '';
  }

  &.margin-top {
    margin-top: 40rpx;
  }
}
::v-deep .u-checkbox {
  width: 100%;
}
::v-deep .u-checkbox__label {
  font-size: 14px;
  color: #303133;
  line-height: 36px;
}
.tip {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 24rpx;
  color: #666666;
  line-height: 36rpx;
  font-style: normal;
  padding: 24rpx 0;
}

.input_with_icon {
  position: relative;

  .suffix-icon {
    position: absolute;
    right: 20rpx;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
  }

  /deep/ .u-input {
    &__input {
      padding-right: 60rpx;
    }
  }
}
.student_box {
  /deep/ .u-cell-item-box {
    background-color: #ffffff;
    flex-direction: row;
    background: #ffffff;
    border-radius: 8rpx;
    border: 2rpx solid #d5d5d5;
  }
}
.action_btn {
  margin-top: 24px;
  display: flex;
  .btn {
    height: 90rpx;
    border-radius: 44rpx;
    border: 1rpx solid #d5d5d5;
    text-align: center;
    line-height: 90rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 500;
    font-size: 30rpx;
    flex: 1;
  }
  .btn1 {
    color: #000000;
    background: #ffffff;
    margin-right: 24rpx;
  }
  .btn2 {
    color: #ffffff;
    background: #0dc160;
  }
}
.duration-section {
  margin-bottom: 20rpx;
  padding: 20rpx;
  border: 1px solid #f0f0f0;
  border-radius: 8rpx;
  background-color: #fafafa;
  display: block; /* 确保垂直布局 */
  width: 100%;
}

.duration-input-row {
  display: flex;
  align-items: center;
  margin-top: 10rpx;

  /deep/ .u-input {
    height: 70rpx; // 确保所有输入框高度一致
  }
}

.duration-option-row {
  margin-bottom: 5rpx;
  display: block;
}

.duration-unit {
  margin-left: 15rpx;
  font-size: 28rpx;
  color: #606266;
  min-width: 60rpx;
}
.range-container {
  display: flex;
  align-items: center;
}
.range-separator {
  margin: 0 20rpx;
  font-size: 28rpx;
}
.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}
.setting-label {
  font-size: 28rpx;
}
.setting-desc {
  font-size: 24rpx;
  color: #999;
  padding: 10rpx 0 30rpx;
}
.weekdays-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}
.weekday-item {
  margin-bottom: 10rpx;
}
.inputview {
  // border-radius: 6rpx;
  // border-radius: 4px;
  // border: 1px solid rgb(220, 223, 230);
  width: 100%;
  font-size: 28rpx;
  min-height: 36px;
  padding: 0px 10px;
  margin-top: 4px;
  text-align: left;
  color: rgb(192, 196, 204);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 成功弹窗样式 */
.success-popup {
  padding: 40rpx;
  background-color: #fff;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-icon {
  margin-bottom: 20rpx;
}

.success-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10rpx;
}

.success-desc {
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 40rpx;
  text-align: center;
}

.success-actions {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.success-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 28rpx;
  border-radius: 8rpx;
}

.success-btn.primary {
  background-color: #0dc160;
  color: #ffffff;
}

.success-btn.default {
  background-color: #f0f0f0;
  color: #303133;
}

.success-btn.link {
  color: #0dc160;
  background-color: transparent;
}

/* 修改单选按钮的样式 */
.class-type-selector {
  display: flex;
  gap: 20rpx;
}

.class-type-item {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #FFFFFF;
  border: 2rpx solid #DCDFE6;
  border-radius: 6rpx;
  transition: all 0.3s;
  cursor: pointer;
}

.class-type-active {
  border-color: #0dc160;
  background-color: rgba(13, 193, 96, 0.1);
}

.radio-circle {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  border: 2rpx solid #DCDFE6;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.class-type-active .radio-circle {
  border-color: #0dc160;
}

.radio-inner {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: #0dc160;
}

.class-type-item text {
  font-size: 28rpx;
  color: #606266;
}

.class-type-active text {
  color: #0dc160;
  font-weight: 500;
}

.type-description {
  margin-top: 20rpx;
  padding: 16rpx;
  background-color: #F8F9FA;
  border-radius: 6rpx;
}

.desc-text {
  font-size: 24rpx;
  color: #909399;
  display: block;
  line-height: 1.4;
}

.class-type-selector {
  display: flex;
  gap: 20rpx;
}

.class-type-item {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 20rpx;
  background: #FFFFFF;
  border: 2rpx solid #DCDFE6;
  border-radius: 6rpx;
  transition: all 0.3s;
}

.text-tips {
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
  line-height: 1.4;
}
</style>
